package com.atguigu.gulimail.search.thread;

import java.util.concurrent.*;

public class ThreadTest {

    public static ExecutorService executor = Executors.newFixedThreadPool(10);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("main.....start......");
//        异步编排
//        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
//            System.out.println("当前线程：" + Thread.currentThread().getId());
//            int i = 10 / 2;
//            System.out.println("运行结果:" + i);
//        }, executor);

//        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
//            System.out.println("当前线程：" + Thread.currentThread().getId());
//            int i = 10 / 0;
//            System.out.println("运行结果:" + i);
//            return i;
//        }, executor).whenComplete((res, exception) -> {
//            // 虽然能得到异常信息，但是没法修改返回数据
//            System.out.println("异步任务完成了....结果是:" + res + ";异常是:" +exception);
//        }).exceptionally(throwable -> {
//            // 可以感知异常，同时返回默认值
//            return 10;
//        });
//        Integer integer = future.get();

//        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
//            System.out.println("当前线程：" + Thread.currentThread().getId());
//            int i = 10 / 0;
//            System.out.println("运行结果:" + i);
//            return i;
//        }, executor).handle((res, thr) -> {
//            if (res != null) {
//                return res * 2;
//            }
//            if (thr != null) {
//                return 0;
//            }
//            return 0;
//        });

//        CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> {
//            System.out.println("当前线程：" + Thread.currentThread().getId());
//            int i = 10 / 4;
//            System.out.println("运行结果:" + i);
//            return i;
//        }, executor).thenRunAsync(() -> {
//            System.out.println("任务2启动了...");
//        }, executor);

//        CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> {
//            System.out.println("当前线程：" + Thread.currentThread().getId());
//            int i = 10 / 4;
//            System.out.println("运行结果:" + i);
//            return i;
//        }, executor).thenAcceptAsync(res -> {
//            System.out.println("任务2启动了..." + res);
//        }, executor);

//        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
//            System.out.println("当前线程：" + Thread.currentThread().getId());
//            int i = 10 / 4;
//            System.out.println("运行结果:" + i);
//            return i;
//        }, executor).thenApplyAsync(res -> {
//            System.out.println("任务2启动了..." + res);
//            return "Hello" + res;
//        }, executor);

        CompletableFuture<Object> future01 = CompletableFuture.supplyAsync(() -> {
            System.out.println("任务1线程：" + Thread.currentThread().getId());
            int i = 10 / 4;
            System.out.println("任务1结束:");
            return i;
        }, executor);

        CompletableFuture<Object> future02 = CompletableFuture.supplyAsync(() -> {
            System.out.println("任务2线程：" + Thread.currentThread().getId());
            try {
                Thread.sleep(3000);
                System.out.println("任务2结束:");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "Hello";
        }, executor);

//        future01.thenAcceptBothAsync(future02,(f1, f2)->{
//            System.out.println("任务3开始...之前的结果：" + f1 + "-->" + f2);
//        } ,executor);

//        CompletableFuture<String> future = future01.thenCombineAsync(future02, (f1, f2) -> {
//            return f1 + ": " + f2 + " -> Haha";
//        }, executor);

//        future01.runAfterEitherAsync(future02, () -> {
//            System.out.println("任务3开始...之前的结果：");
//        }, executor);

//        future01.acceptEitherAsync(future02, (res) -> {
//            System.out.println("任务3开始...之前的结果：");
//        }, executor);

//        CompletableFuture<String> future = future01.applyToEitherAsync(future02, (res) -> {
//            System.out.println("任务3开始...之前的结果：");
//            return res.toString() + "->哈哈";
//        }, executor);



        CompletableFuture<String> futureImg = CompletableFuture.supplyAsync(() -> {
            System.out.println("查询商品的图片信息");
            return "hello.jpg";
        });
        CompletableFuture<String> futureAttr = CompletableFuture.supplyAsync(() -> {
            System.out.println("查询商品的属性");
            return "黑色+256G";
        });
        CompletableFuture<String> futureDesc = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(3000);
                System.out.println("查询商品介绍");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "华为";
        });

//        CompletableFuture<Void> allOf = CompletableFuture.allOf(futureImg, futureAttr, futureDesc);
        CompletableFuture<Object> anyOf = CompletableFuture.anyOf(futureImg, futureAttr, futureDesc);

        anyOf.get();

        System.out.println("main.....end......");
    }

    public void thread(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("main.....start......");
        /*
           继承Thread
            Thread01 thread = new Thread01();
            thread.start();
           实现Runnable接口
            Runnable01 runnable01 = new Runnable01();
            new Thread(runnable01).start();
           实现Callable接口+futureTask 可以拿到返回结果 可以处理异常
            FutureTask<Integer> futureTask = new FutureTask<>(new Callable01());
            new Thread(futureTask).start();
            Integer integer = futureTask.get();
           线程池[ExecutorService]
            给线程池直接提交任务
             service.execute(new Runnable01());
            创建
             Executors
             new ThreadPoolExecutor(
                              int corePoolSize,核心线程数，创建好以后就准备就绪的线程数量，就等待来接受异步任务去执行
                              int maximumPoolSize,最大线程数量；控制资源
                              long keepAliveTime,存活时间 如果当前线程数量大于核心数量，只要非核心线程空闲大于指定的keepAliveTime，则释放空闲的线程
                              TimeUnit unit,时间单位
                              BlockingQueue<Runnable> workQueue,阻塞队列 如果任务有很多，就会将目前多的任务放在队列里面。只要有线程空闲，就
                              会去队列里面取出新的任务继续执行
                              ThreadFactory threadFactory,线程的创建工厂
                              RejectedExecutionHandler handler 如果阻塞队列满了，按照指定的拒绝策略拒绝执行任务
                              );
            工作顺序
             线程池创建，准备好core数量的核心线程，准备接受任务

        * */
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5,
                200,
                10,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(100000),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());

        //Executors.newCachedThreadPool();
        //Executors.newFixedThreadPool();
        //Executors.newScheduledThreadPool();
        //Executors.newSingleThreadExecutor();

        System.out.println("main.....end......");
    }

    public static class Thread01 extends Thread {
        @Override
        public void run() {
            System.out.println("当前线程：" + Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("运行结果:" + i);
        }
    }

    public static class Runnable01 implements Runnable {

        @Override
        public void run() {
            System.out.println("当前线程：" + Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("运行结果:" + i);
        }
    }

    public static class Callable01 implements Callable<Integer> {

        @Override
        public Integer call() throws Exception {
            System.out.println("当前线程：" + Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("运行结果:" + i);
            return i;
        }
    }
}
